package com.springstudy.redisListener;

import com.springstudy.redis.RedisApplication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

/**
 * @author chenrongrong
 * @since 2020/4/8 16:27
 */
@SpringBootApplication
public class RedisListenerConfig {

    // RedisTemplate
    @Autowired
    private RedisTemplate redisTemplate = null;

    // Redis链接工厂
    @Autowired
    private RedisConnectionFactory connectionFactory = null;

    // 消息监听器
    @Autowired
    private com.springstudy.redisListener.RedisMessageListener redisMessageListenr = null;

    // 任务池
    @Autowired
    private ThreadPoolTaskScheduler taskScheduler = null;

    /**
     * 创建任务池，运行线程等待处理Redis消息
     *
     * @return
     */
    @Bean
    public ThreadPoolTaskScheduler initTaskScheduler() {
        if(taskScheduler != null) {
            return taskScheduler;
        }
        taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(20);
        return taskScheduler;
    }

    /**
     * 定义Redis的监听容器
     *
     * @return
     */
    @Bean
    public RedisMessageListenerContainer initRedisContainer() {
        System.out.println("初始化redis容器");
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        // 设置Redis连接工厂
        container.setConnectionFactory(connectionFactory);
        // 设置运行任务池
        container.setTaskExecutor(initTaskScheduler());
        // 定义监听渠道，名称为topic1
        Topic topic = new ChannelTopic("topic1");
        // 使用监听器监听Redis消息
        container.addMessageListener(redisMessageListenr, topic);
        return container;
    }

    public static void main(String[] args) {
        SpringApplication.run(RedisApplication.class, args);
    }
}
